﻿using System;
using System.Web;

namespace DNT.RavenQA.Web.Infrastructure.Security
{
    /// <remarks>
    /// HACK: http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx
    /// </remarks>
    public class SuppressFormsAuthenticationRedirectModule : IHttpModule
    {
        private static readonly Object SuppressAuthenticationKey = new Object();

        public static void SuppressAuthenticationRedirect(HttpContext context)
        {
            context.Items[SuppressAuthenticationKey] = true;
        }

        public static void SuppressAuthenticationRedirect(HttpContextBase context)
        {
            context.Items[SuppressAuthenticationKey] = true;
        }

        public void Init(HttpApplication context)
        {
            context.PostReleaseRequestState += OnPostReleaseRequestState;
            context.EndRequest += OnEndRequest;
        }

        private static void OnPostReleaseRequestState(Object source, EventArgs args)
        {
            var context = (HttpApplication) source;
            var response = context.Response;
            var request = context.Request;

            if (response.StatusCode == 401 && request.Headers["X-Requested-With"] == "XMLHttpRequest")
                SuppressAuthenticationRedirect(context.Context);
        }

        private static void OnEndRequest(Object source, EventArgs args)
        {
            var context = (HttpApplication) source;
            var response = context.Response;

            if (!context.Context.Items.Contains(SuppressAuthenticationKey))
                return;

            response.TrySkipIisCustomErrors = true;
            response.ClearContent();
            response.StatusCode = 401;
            response.RedirectLocation = null;
        }

        public void Dispose() { }
    }
}